﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TreeRenderingWithVisitor
{
    class HtmlRenderer : IRenderer
    {
        private StringBuilder _builder = new StringBuilder();

        public string Render(ITree tree)
        {
            InUL(() =>
            {
                InLI(() =>
                {
                    _Render(tree);
                }, tree);
            }, tree);

            return _builder.ToString();
        }

        private void _Render(ITree tree)
        {
            if (tree.Children.Count > 0)
            {
                InUL(() =>
                 {
                     foreach (var child in tree.Children)
                     {
                         InLI(() =>
                         {
                             _Render(child);
                         }, child);
                     }

                 }, tree);
            }
        }

        private void InUL(Action action, ITree node)
        {
            _builder.Append("<ul>");
            action();
            _builder.Append("</ul>");
        }

        private void InLI(Action action, ITree node)
        {
            _builder.Append("<li id=").Append(node.Id).Append(">");
            _builder.Append(node.Name);
            action();
            _builder.Append("</li>");

        }
    }
}

